import { useEffect, useRef } from 'react'
import { useSetState } from 'ahooks'
import { fetchArticleCategory, fetchTags } from '@/api'

export const useMounted = () => {
  const mountedRef = useRef(false)
  useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  }, [])
  return () => mountedRef.current
}

// 分类列表
export function useArticleCategory(params?: any) {
  const [state, setState] = useSetState<{ categoryList: any, loading: boolean, run: any }>({ categoryList: [], loading: false, run: () => { } })
  const isMounted = useMounted()

  useEffect(() => {
    const fetchData = async () => {
      const { rows } = await fetchArticleCategory(params)

      if (!isMounted() || !rows) {
        return
      }

      setState({ categoryList: rows[0]?.children, loading: false })
    }

    setState({ loading: true, run: fetchData })
    fetchData()
  }, [])

  return state
}

// 分类列表
export function useTags(params?: any) {
  const [state, setState] = useSetState<{ tagsList: any, loading: boolean, run: any }>({ tagsList: [], loading: false, run: () => { } })
  const isMounted = useMounted()

  useEffect(() => {
    const fetchData = async () => {
      const { rows } = await fetchTags(params)

      if (!isMounted()) {
        return
      }

      setState({ tagsList: rows, loading: false })
    }

    setState({ loading: true, run: fetchData })
    fetchData()
  }, [])

  return state
}
